//
//  ComposeViewController.swift
//  微博三天
//
//  Created by jessica on 15/11/19.
//  Copyright © 2015年 jessica. All rights reserved.
//

import UIKit
import SnapKit

//(30)便利UIBarButtonItem+Extension里面添加actionNamae,target
//(28)
import SVProgressHUD

private let registerCellId = "registerCellId"

class ComposeViewController: UIViewController {

//    监听方法
    
    //(32)添加图片的出现在工具栏上
    @objc private func selectPicture(){
    
    selectVC.view.snp_updateConstraints { (make) -> Void in
        //键盘高度224,工具栏的高度40,图片控制器视图高度80(可调整)
        make.height.equalTo(224 + 132 + 40)//间隔必须要,否则就会
        }

    }
    
    @objc private func close (){
    
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    @objc private func send() {
        
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        guard let token = userAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus("客官,您还未登陆哦噢噢噢")
            return
        }
        
        if selectVC.imageList.count >= 1 {
            let imageData = UIImagePNGRepresentation(selectVC.imageList[0])
            let parmaters = ["access_token": token,"status": textView.text]
            NetworkTools.shardTools.uploadImage(urlString, parmaters: parmaters, imageData: imageData!, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus(ApperrorTip)
                    return
                }
                
                SVProgressHUD.showSuccessWithStatus("发布Weibo成功")
            })
        }
        
    }
//        let paraments = ["access_token" : token , "status" : textView.text]
//        NetworkTools.shardTools.requestJsonDict(.POST, urlString: urlString, paraments: paraments) { (result, error) -> () in
//            //错误提示
//            if error != nil{
//            
//                SVProgressHUD.showErrorWithStatus(ApperrorTip)
//            return
//            }
//            SVProgressHUD.showErrorWithStatus("~发布weibo成功~")
////返回主控制器页面 ,在AppDelegate里面把跟控制器换回来
//            self.dismissViewControllerAnimated(true, completion: nil)
//            return
//        }
    
//    }
    
   
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        //(1)
        setupUI()
    }
    //(2)
    private func setupUI(){
    
        setNavBar()
        //(7)添加文本输入框
        setupTextView()
        //(13)添加工具条
        setupToolBar()
        //(33)添加图片选择器控制器视图
        selectPictureView()
        
        //(19)注册通知
        registerNotification()
    }
    
    //(34)
    
    private func selectPictureView(){
    //添加子控制器 ,懒加载的记得吗?就是PictureViewController
        addChildViewController(selectVC)
        //添加视图
        view.addSubview(selectVC.view)
        
        //视图层级结构
        view.bringSubviewToFront(toolBar)
        //子控制器进行约束布局
        selectVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(00)
        }
    }
    //(20)添加通知
    private func registerNotification(){
    
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    }
//    (21)移除通知
    
    deinit{
    
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
//
    //(22)响应通知方法
    
    @objc private func keyboardWillChange(nn : NSNotification){
    
    //(23)获取动画事件
        let duration = nn.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let rect = (nn.userInfo![UIKeyboardFrameEndUserInfoKey]as! NSValue).CGRectValue()
        
        //(24)修改约束
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        //(25)强打出来
        UIView.animateWithDuration(duration) { () -> Void in
        
        //强制刷新
            self.view.layoutIfNeeded()
        }
        
    }
    

//
  //(7)懒加载控件
    private lazy var textView : UITextView = {
        
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.backgroundColor = UIColor.randomColor()
        //        tv.text = "生活如此多娇"
        tv.textColor = UIColor.darkGrayColor()
        //(26)设置代理,发布
        tv.delegate = self
        //(11)键盘拉动取消模式
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //(11)设置弹簧效果才会取消键盘模式
        tv.alwaysBounceVertical = true
        
        return tv
        
        }()
    
    //(9)占位文本
    private lazy var placeHolderLabel : UILabel = UILabel(title: "生活如此多娇...", size: 18, color: UIColor.lightGrayColor())

    //(12)工具条
    private lazy var toolBar : UIToolbar = UIToolbar()
    
    //(31)图片选择器
    private lazy var selectVC : PictureViewController = PictureViewController()
    
}

//(27)扩展 文本代理
extension ComposeViewController : UITextViewDelegate {
   //调用此方法
    func textViewDidChangeSelection(textView: UITextView) {
        //设置占位文本隐藏
        placeHolderLabel.hidden = textView.hasText()//有文本就隐藏占位文本
        //设置按钮交互,有文本就可以交互,否则不行
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
}

//扩展 ,直观
extension ComposeViewController {
   
    private func setupToolBar (){
    //(13)添加底部工具条
    view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(view)
            make.height.equalTo(40)
        }
        
        //(14)设置toolBar的按钮一级点击事件
        //初始化数组
        var items = [UIBarButtonItem]()
        //(15)添加UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName" : "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_add_background"]]
        
          //(16)遍历
        for dict in itemSettings {
            //(18)添加一个便利方法,一句话搞定
//            let item = UIBarButtonItem(imageName: dict["imageName"]!)
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            
            //(17)添加弹簧,彼此间隔开
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        //(17)去除最后一个弹簧
        items.removeLast()
      //添加到工具栏,items第一个是系统的,第二个是自己命名的
    toolBar.items = items
        
    }
    
    //(8)设置约束
    
    private func setupTextView(){
        
        view.addSubview(textView)
        textView.backgroundColor = UIColor.yellowColor()
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(view.bounds.size.height / 3)
        }
        //(10)占位文本约束
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    //设置导航条
    private func setNavBar(){
        //(3)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        //(3)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        //(3)设置文本的  (4)MainTableViewController中跳转根控制器设置
        let titleVieww = UIView(frame: CGRectMake(0, 0, 200, 40))
        //    titleVieww.backgroundColor = UIColor.lightGrayColor()
        navigationItem.titleView = titleVieww
        
        
        //(5)添加标题跟副标题
        let titleLabel = UILabel(title: "发微博", size: 16, color: UIColor.blackColor())
        let nameLabel = UILabel(title: userAccountViewModel().userName ?? "", size: 12, color: UIColor.greenColor())
        
        //(6)添加
        titleVieww.addSubview(titleLabel)
        titleLabel.addSubview(nameLabel)
        //(6)设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleVieww)
            make.centerX.equalTo(titleVieww.snp_centerX)
            
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleVieww)
            make.centerX.equalTo(titleLabel.snp_centerX)
        }
    
    }
}